"""
    Controller for viewing exists and editing agreements.
    Also contains a lot of huge awful papers for agreement creation:
    for existing student, with migration and so on.
"""

from turbogears import widgets, identity, validate, expose, redirect, validators, flash
from turbogears.widgets import TextField
from mnemoply import model
from mnemoply.controllers import Report
from mnemoply.mass_actions import MassAction, MassActionForm
from mnemoply.controllers.lookup import LookupController, TableCol, TableLookupDataSource
from mnemoply.controllers.crud import CRUDController, ItemTab
from mnemoply.widgets import DictionaryField, fields_for, FieldGroup, \
    TemporaryPaymentField, StudentField, CustomerField, createPlanField, \
    DiscontCardField
from mnemoply.utils import objs2ids, LocalMenuItem, Wrapper, cleanup_kw
from sqlobject.sqlbuilder import AND, SQLConstant
from mnemoply.model.field import TemporaryPaymentRecord, PaymentRecord

class MAPrint(MassAction):
    target_class = model.StudentAgreement
    name = "agreement_print"
    title = _("Print")
    read_only = True

    def call(self, objs):
        print 'SSSSSSS'
        return Report.generate('AgreementPrint',
            ids=objs2ids(objs),
        )
class MADelete(MassAction):
    target_class = model.StudentAgreement
    name = "agreement_delete"
    title = _("Delete")
    #read_only = True

    def call(self, objs):
        result = True
        for o in  objs:
            id=o.id
            pays = model.PaymentRecord.selectBy(studentAgreement=id)
            tmp_pays = model.TemporaryPaymentRecord.selectBy(studentAgreement=id)
            if [pay for pay in pays if pay.amount>0]:
                result = False
                continue
            if [pay for pay in tmp_pays if pay.payment>0]:
                result = False
                continue
            try: 
                for pay in pays:
                    if pay.amount == 0:
                        pay.destroySelf()
                for pay in tmp_pays:
                    if pay.payment == 0:
                        pay.studentAgreement = None
                    pay.student = None
                if [type( rf) for rf in o.findReferences() if not isinstance(rf,model.EducationInfo)]:
                    result = False
                    continue
                for info in model.EducationInfo.selectBy(studentAgreement=id):         
                    info.destroySelf()
                o.destroySelf()
            except:
                result = False
        self.successfully_execute = result
            
 
class MAChangeCustomerTariff(MassAction):
    target_class = model.StudentAgreement
    name = "change_customer_tariff"
    title = _("Change customer tariff")

    form = MassActionForm(name=name,
        fields=[
            DictionaryField(
                name="tariff_id",
                model_object_name='CustomerTariff',
                not_empty=True,
                label=_("Change"),
            ),
        ]
    )

    def call(self, objs, tariff_id):
        tariff = model.CustomerTariff.get(tariff_id)
        for agr in objs:
            agr.customerTariff = tariff

class MAChangeCustomerTariff1(MassAction):
    target_class = model.StudentAgreement
    name = "change_customer_tariff1"
    title = _("Change customer tariff1")

    form = MassActionForm(name=name,
        fields=[
            DictionaryField(
                name="tariff_id",
                model_object_name='CustomerTariff',
                not_empty=True,
                label=_("Change"),
            ),
        ]
    )

    def call(self, objs, tariff_id):
        tariff = model.CustomerTariff.get(tariff_id)
        for agr in objs:
            agr.customerTariff = tariff

class FirstDiscontTab(ItemTab):
    title = _("First discont")
    name = "fisrt_discont_tab"
    template = "../agreement_first_discont_tab"
    edit_widget = None

    edit_fields = [
        'discontID',
        'partnerID',
        'cardID',
        'isAlreadyUse',
        'comment',
        ]

    save_action = 'save_discont'
    save_action_text = _("Save")
    add_action = 'add_discont'
    add_action_text = _("Add")

    def __init__(self):
        self.edit_fields = [FieldGroup(fields=self.edit_fields)]
        self.edit_widget = widgets.TableForm(fields=fields_for(model.FirstDiscont, self.edit_fields))

    def setting_form(self):
        return self.edit_widget

    @identity.require(identity.has_any_permission('dba', 'StudentAgreement/edit'))
    @validate(form=setting_form)
    @expose()
    def save_discont(self, obj, tg_errors=None, **data):
        if tg_errors:
            return self.controller.show(obj)

        info = model.FirstDiscont.selectBy(agreement=obj)
        if len(list(info)):
            info = model.FirstDiscont.selectBy(agreement=obj)[0]
            info.set(**data)

        raise redirect("./")

    @identity.require(identity.has_any_permission('dba', 'StudentAgreement/edit'))
    @validate(form=setting_form)
    @expose()
    def add_discont(self, obj, tg_errors=None, **data):
        if tg_errors:
            return self.controller.show(obj)

        info = model.FirstDiscont.selectBy(agreement=obj)
        if not len(list(info)):
            data["agreementID"] = unicode(obj.id)
            model.FirstDiscont(**data)

        raise redirect("./")

class EducationInfoTab(ItemTab):
    title = _("Education info")
    name = "info_tab"
    template = "../agreement_info_tab"
    edit_widget = None

    edit_fields = [
        'possibleDay',
        'unpossibleDay',
        'friends',
        'officeID',
        'testResultBasic',
        'testResultProf',
        'comment',
        ]

    save_action = 'save_info'
    save_action_text = _("Save")
    add_action = 'add_info'
    add_action_text = _("Add")

    def __init__(self):
        self.edit_fields = [FieldGroup(fields=self.edit_fields)]
        self.edit_widget = widgets.TableForm(fields=fields_for(model.EducationInfo, self.edit_fields))

    def setting_form(self):
        return self.edit_widget

    @identity.require(identity.has_any_permission('dba', 'StudentAgreement/edit'))
    @validate(form=setting_form)
    @expose()
    def save_info(self, obj, tg_errors=None, **data ):
        if tg_errors:
            return self.controller.show(obj)

        info = model.EducationInfo.selectBy(studentAgreement=obj)
        if len(list(info)):
            info = model.EducationInfo.selectBy(studentAgreement=obj)[0]
            info.set(**data)

        raise redirect("./")

    @identity.require(identity.has_any_permission('dba', 'StudentAgreement/edit'))
    @validate(form=setting_form)
    @expose()
    def add_info(self, obj, tg_errors=None, **data ):
        if tg_errors:
            return self.controller.show(obj)

        info = model.EducationInfo.selectBy(studentAgreement=obj)
        if not len(list(info)):
            data["studentAgreementID"] = unicode(obj.id)
            model.EducationInfo(**data)

        raise redirect("./")

def ReadonlyDateField(label):
    return TextField(
        label=label,
        attrs=dict(disabled=True),
    )

def DateField(label):
    return widgets.CalendarDatePicker(
        label=label,
        calendar_lang='ru',
        format='%d.%m.%Y',
    )

class AgreementPaperField(widgets.WidgetsList):
    temppr = DictionaryField(model_object_name='TemporaryPaymentRecord', not_empty=True, label=_("Payment number"), name="temppr")
    organization_id = DictionaryField(model_object_name='Organization', not_empty=True, label=_("Organization"))
    trend_id = DictionaryField(model_object_name='Trend', not_empty=True, label=_("Trend"))
    customer_tariff_id = DictionaryField(model_object_name='CustomerTariff', not_empty=True, label=_("Customer tariff"))
    information_source_id = DictionaryField(model_object_name='InformationSource', not_empty=True, label=_("Information source"))
    event_id = DictionaryField(model_object_name='Event', not_empty=True, label=_("Event"))

    customer_surname = TextField(label=_("Customer surname"))
    customer_forename = TextField(label=_("Customer forename"))
    customer_patronymic = TextField(label=_("Customer patronymic"))
    customer_phone = TextField(label=_("Customer phone"), attrs={'size': 64, 'maxlength': 64})
    customer_email = TextField(label=_("Customer e-mail"), attrs={'size': 64, 'maxlength': 64})

    student_surname = TextField(label=_("Student surname"))
    student_forename = TextField(label=_("Student forename"))
    student_patronymic = TextField(label=_("Student patronymic"))
    student_birthday = DateField(_('Birthday'))
    student_sex = widgets.SingleSelectField(label="Gender", options=[('male', _('Male')), ('female', _('Female')), ])

    student_school_name = TextField(label=_("School name"))
    student_school_form = TextField(label=_("School form"))

    register_id = DictionaryField(model_object_name='CashRegister', not_empty=True, label=_("Cash register"), name="register_id")
    possible_days = DictionaryField(model_object_name='PossibleDayValues',
                                    label=_("Possible day"), name="possible_days")
    unpossible_days = DictionaryField(model_object_name='PossibleDayValues',
                                      label=_("Unpossible day"), name="unpossible_days")

    testResultBasic = TextField(label=_("Basic test result"))
    testResultProf = TextField(label=_("Prof. test result"))

    initial_plan_id = createPlanField(label=_("Initial plan"))

    date_enter_agreement_view = ReadonlyDateField(_("Date enter agreement "))
    date_enter_agreement = widgets.HiddenField(label=_("Date enter agreement "))

class AgreementPaperSchema(validators.Schema):
    student_surname = validators.NotEmpty()
    student_forename = validators.NotEmpty()
    student_birthday = validators.All(validators.NotEmpty, validators.DateTimeConverter(format="%d.%m.%Y"))
    student_sex = validators.NotEmpty()
    student_school_form = validators.Int(not_empty=True)
    testResultBasic = validators.Int(not_empty=False)
    customer_surname = validators.NotEmpty()

class AgreementPaperWithStudent(widgets.WidgetsList):
    temppr = DictionaryField(model_object_name='TemporaryPaymentRecord', not_empty=True, label=_("Payment number"), name="temppr")
    organization_id = DictionaryField(model_object_name='Organization', not_empty=True, label=_("Organization"))
    trend_id = DictionaryField(model_object_name='Trend', not_empty=True, label=_("Trend"))
    customer_tariff_id = DictionaryField(model_object_name='CustomerTariff', not_empty=True, label=_("Customer tariff"))
    information_source_id = DictionaryField(model_object_name='InformationSource', not_empty=True, label=_("Information source"))
    event_id = DictionaryField(model_object_name='Event', not_empty=True, label=_("Event"))

    customer = DictionaryField(model_object_name='Customer', not_empty=True, label=_("Customer"))

    student = DictionaryField(model_object_name='Student', not_empty=True, label=_("Student"))

    initial_plan_student_wish_id = createPlanField(label=_("Initial plan student wish"))

    date_enter_agreement_view = ReadonlyDateField(_("Date enter agreement "))
    date_enter_agreement = widgets.HiddenField(label=_("Date enter agreement "))

    register_id = DictionaryField(model_object_name='CashRegister', not_empty=True, label=_("Cash register"), name="register_id")

class AgreementPaperWithStudentSchema(validators.Schema):
    testResultBasic = validators.Int(not_empty=False)

class AgreementPaperWithStudentWithoutCustomer(widgets.WidgetsList):
    temppr = DictionaryField(model_object_name='TemporaryPaymentRecord', not_empty=True, label=_("Payment number"), name="temppr")
    organization_id = DictionaryField(model_object_name='Organization', not_empty=True, label=_("Organization"))
    trend_id = DictionaryField(model_object_name='Trend', not_empty=True, label=_("Trend"))
    information_source_id = DictionaryField(model_object_name='InformationSource', not_empty=True, label=_("Information source"))
    event_id = DictionaryField(model_object_name='Event', not_empty=True, label=_("Event"))
    customer_tariff_id = DictionaryField(model_object_name='CustomerTariff', not_empty=True, label=_("Customer tariff"))
    student = DictionaryField(model_object_name='Student', not_empty=True, label=_("Student"))

    customer_surname = TextField(label=_("Customer surname"))
    customer_forename = TextField(label=_("Customer forename"))
    customer_patronymic = TextField(label=_("Customer patronymic"))
    customer_phone = TextField(label=_("Customer phone"), attrs={'size': 64, 'maxlength': 64})
    customer_email = TextField(label=_("Customer e-mail"), attrs={'size': 64, 'maxlength': 64})

    register_id = DictionaryField(model_object_name='CashRegister', not_empty=True, label=_("Cash register"), name="register_id")

    initial_plan_student_wish_id = createPlanField(label=_("Initial plan student wish"))

    date_enter_agreement_view = ReadonlyDateField(_("Date enter agreement "))
    date_enter_agreement = widgets.HiddenField(label=_("Date enter agreement "))

class AgreementPaperWithStudentWithoutCustomerSchema(validators.Schema):
    customer_surname = validators.NotEmpty()
    testResultBasic = validators.Int(not_empty=False)

class AgreementPaperFieldWithoutStudentWithCustomer(widgets.WidgetsList):
    temppr = DictionaryField(model_object_name='TemporaryPaymentRecord', not_empty=True, label=_("Payment number"), name="temppr")
    organization_id = DictionaryField(model_object_name='Organization', not_empty=True, label=_("Organization"))
    trend_id = DictionaryField(model_object_name='Trend', not_empty=True, label=_("Trend"))
    information_source_id = DictionaryField(model_object_name='InformationSource', not_empty=True, label=_("Information source"))
    event_id = DictionaryField(model_object_name='Event', not_empty=True, label=_("Event"))
    customer_tariff_id = DictionaryField(model_object_name='CustomerTariff', not_empty=True, label=_("Customer tariff"))

    customer = DictionaryField(model_object_name='Customer', not_empty=True, label=_("Customer"))

    student_surname = TextField(label=_("Student surname"))
    student_forename = TextField(label=_("Student forename"))
    student_patronymic = TextField(label=_("Student patronymic"))
    student_birthday = DateField(_('Birthday'))
    student_sex = widgets.SingleSelectField(label="Gender", options=[('male', _('Male')), ('female', _('Female')), ])

    student_school_name = TextField(label=_("School name"))
    student_school_form = TextField(label=_("School form"))

    register_id = DictionaryField(model_object_name='CashRegister', not_empty=True, label=_("Cash register"), name="register_id")

    possible_days = DictionaryField(model_object_name='PossibleDayValues',
                                    label=_("Possible day"), name="possible_days")
    unpossible_days = DictionaryField(model_object_name='PossibleDayValues',
                                      label=_("Unpossible day"), name="unpossible_days")

    testResultBasic = TextField(label=_("Basic test result"))
    testResultProf = TextField(label=_("Prof. test result"))

    initial_plan_id = createPlanField(label=_("Initial plan"))

    date_enter_agreement_view = ReadonlyDateField(_("Date enter agreement "))
    date_enter_agreement = widgets.HiddenField(label=_("Date enter agreement "))

class AgreementPaperFieldWithoutStudentWithCustomerSchema(validators.Schema):
    student_surname = validators.NotEmpty()
    student_forename = validators.NotEmpty()
    student_birthday = validators.All(validators.NotEmpty, validators.DateTimeConverter(format="%d.%m.%Y"))
    student_sex = validators.NotEmpty()
    student_school_form = validators.Int(not_empty=True)
    testResultBasic = validators.Int(not_empty=False)

class AgreementController(LookupController, CRUDController):
    model_object = model.StudentAgreement
    lookup_columns = [
        TableCol(name='faculty', caption=_("Faculty")),
        TableCol(name='group_title', caption=_('Group')),
        TableCol(name='student', caption=_('Student')),
        TableCol(name='customer', caption=_('Customer')),
        TableCol(name='year', caption=_('Year')),
        TableCol(name='initial_plan', caption=_('Initial plan')),
        TableCol(name='date_enter_agreement', caption=_('Date enter agreement'), hidden=True),
        TableCol(name='date_begin_agreement', caption=_('Date begin agreement'), hidden=True),
        TableCol(name='date_end_agreement', caption=_('Date end agreement'), hidden=True),
        TableCol(name='date_cancellation_agreement', caption=_('Date cancellation agreement'), hidden=True),
        TableCol(name='organization', caption=_('Organization'), hidden=True),
        TableCol(name='trend', caption=_('Trend'), hidden=True),
        TableCol(name='school_form', caption=_('School form'), hidden=True),
        TableCol(name='coupon_number', caption=_('Coupon number'), hidden=True),
        ]

    item_tabs = [EducationInfoTab(), FirstDiscontTab()]

    edit_fields = [
        'studentID',
        'customerID',
        'initialPlanID',
        'initialPlanStudentWishID',
        'customerTariffID',
        'trendID',
        'agreementTypeID',
        'informationSourceID',
        'eventID',
        'year',  'dateBeginAgreement', 'dateEndAgreement',
        ]

    view_fields = edit_fields + ['organizationID']

    create_form = widgets.TableForm(
        name="AgreementPaper",
        fields=AgreementPaperField(),
        validator=AgreementPaperSchema(),
        submit_text=_("Add"),
        action='create_agreement',
    )

    create_form_with_student = widgets.TableForm(
        name="AgreementPaperWithStudent",
        fields=AgreementPaperWithStudent(),
        validator=AgreementPaperWithStudentSchema(),
        submit_text=_("Add"),
        action='create_agreement_with_student',
    )

    create_form_with_student_without_customer = widgets.TableForm(
        name="AgreementPaperWithStudentWithoutCustomer",
        fields=AgreementPaperWithStudentWithoutCustomer(),
        validator=AgreementPaperWithStudentWithoutCustomerSchema(),
        submit_text=_("Add"),
        action='create_agreement_with_student_without_customer',
    )

    create_form_without_student_with_customer = widgets.TableForm(
        name="AgreementPaperFieldWithoutStudentWithCustomer",
        fields=AgreementPaperFieldWithoutStudentWithCustomer(),
        validator=AgreementPaperFieldWithoutStudentWithCustomerSchema(),
        submit_text=_("Add"),
        action='create_agreement_without_student_with_customer',
    )

    def __init__(self, data_source=TableLookupDataSource('student_agreement_lookup')):
        LookupController.__init__(self,
            data_source=data_source,
            columns=self.lookup_columns,
            mass_actions_class=self.model_object,
            title=self.model_object.model_title,
            mass_actions_class_names=[
                "MAPrint",
                "MAChangeCustomerTariff",
                "MADelete",
                ],
        )
        CRUDController.__init__(self, model_object=self.model_object)
        self.local_menu = []

    @expose("genshi:mnemoply.templates.create_agreement")
    def show_form(self, **kw):
        return dict(form=self.create_form, kw=kw)

    @expose("genshi:mnemoply.templates.create_agreement")
    def show_form_for_exist_student(self, **kw):
        return dict(form=self.create_form_with_student, kw=kw)

    @expose("genshi:mnemoply.templates.create_agreement")
    def show_form_with_student_without_customer(self, **kw):
        return dict(form=self.create_form_with_student_without_customer, kw=kw)

    @expose("genshi:mnemoply.templates.create_agreement")
    def show_form_without_student_with_customer(self, **kw):
        return dict(form=self.create_form_without_student_with_customer, kw=kw)

    @validate(form=create_form)
    @expose()
    def create_agreement(self, tg_errors=None, **kw):
        if tg_errors:
            return self.show_form()

        (student, agreement, education_info) = self.create_objects(**kw)
        kw = Wrapper(kw)

        temppr_flash = self.create_temppr(kw, student, agreement, education_info)

        link = ' link:%s:/StudentAgreement/%d/' % (_('view'), agreement.id)
        flash(_('Record "%s" added!') % agreement.title + link + temppr_flash)

        raise redirect("/TemporaryPaymentRecord")

    @validate(form=create_form_with_student)
    @expose()
    def create_agreement_with_student(self, tg_errors=None, **kw):
        if tg_errors:
            return self.show_form_for_exist_student()

        kw = Wrapper(cleanup_kw(kw))
        student = model.Student.get(int(kw.student))
        customer = model.Customer.get(int(kw.customer))

        agreement, education_info = self.create_agreement_and_education_info(kw, student, customer)
        temppr_flash = self.create_temppr(kw, student, agreement, education_info)

        link = ' link:%s:/StudentAgreement/%d/' % (_('view'), agreement.id)
        flash(_('Record "%s" added!') % agreement.title + link + temppr_flash)

        raise redirect("/TemporaryPaymentRecord")

    @validate(form=create_form_with_student_without_customer)
    @expose()
    def create_agreement_with_student_without_customer(self, tg_errors=None, **kw):
        if tg_errors:
            return self.show_form_with_student_without_customer()

        kw = Wrapper(cleanup_kw(kw))
        student = model.Student.get(int(kw.student))
        customer = model.Customer(
            surname=kw.customer_surname,
            forename=kw.customer_forename,
            patronymic=kw.customer_patronymic,
            phone=kw.customer_phone,
            email=kw.customer_email
        )

        agreement, education_info = self.create_agreement_and_education_info(kw, student, customer)
        temppr_flash = self.create_temppr(kw, student, agreement, education_info)

        link = ' link:%s:/StudentAgreement/%d/' % (_('view'), agreement.id)
        flash(_('Record "%s" added!') % agreement.title + link + temppr_flash)

        raise redirect("/TemporaryPaymentRecord")

    @validate(form=create_form_without_student_with_customer)
    @expose()
    def create_agreement_without_student_with_customer(self, tg_errors=None, **kw):
        if tg_errors:
            return self.show_form_without_student_with_customer()

        kw = Wrapper(cleanup_kw(kw))
        student = model.Student(
            surname=kw.student_surname,
            forename=kw.student_forename,
            patronymic=kw.student_patronymic,
            birthday=kw.student_birthday,
            gender=kw.student_sex,
            schoolName=kw.student_school_name,
            schoolForm=kw.student_school_form
        )
        customer = model.Customer.get(int(kw.customer))

        agreement, education_info = self.create_agreement_and_education_info(kw, student, customer)
        temppr_flash = self.create_temppr(kw, student, agreement, education_info)

        link = ' link:%s:/StudentAgreement/%d/' % (_('view'), agreement.id)
        flash(_('Record "%s" added!') % agreement.title + link + temppr_flash)

        raise redirect("/TemporaryPaymentRecord")

    def create_temppr(self, kw, student, agreement, education_info):
        agreement.year += 1

        register = model.CashRegister.get(int(kw.register_id))
        day = None
        if kw.get('possible_days') and kw.possible_days is not u'':
            day = model.PossibleDayValues.get(int(kw.possible_days))

        if day is not None:
            education_info.possibleDay = day.title

        unpossibleDay = None
        if kw.get('unpossible_days') and kw.unpossible_days is not u'':
            unpossibleDay = model.PossibleDayValues.get(int(kw.unpossible_days))

        if unpossibleDay is not None:
            education_info.unpossibleDay = unpossibleDay.title

        education_info.office = register.office  # TODO: ??? EducationInfo.office -> EducationInfo.register

        # Fill temporary payment record
        temppr_flash = _(" Temporary agreement not assigned.")
        if kw.temppr is not None:
            temppr = model.TemporaryPaymentRecord.get(kw.temppr)
            if temppr.studentAgreement is None:
                temppr.studentAgreement = agreement
                temppr.student = student
                temppr_flash = _(" Temporary agreement #%d used.") % temppr.id
                if temppr.register is not None:
                    register = temppr.register
                model.PaymentRecord(student=student, studentAgreement=agreement,
                    amount=temppr.payment, register=register, date=temppr.date)
        return temppr_flash

    def create_objects(self, **kw):
        kw = Wrapper(cleanup_kw(kw))

        student = model.Student(
            surname=kw.student_surname,
            forename=kw.student_forename,
            patronymic=kw.student_patronymic,
            birthday=kw.student_birthday,
            gender=kw.student_sex,
            schoolName=kw.student_school_name,
            schoolForm=kw.student_school_form
        )

        customer = model.Customer(
            surname=kw.customer_surname,
            forename=kw.customer_forename,
            patronymic=kw.customer_patronymic,
            phone=kw.customer_phone,
            email=kw.customer_email
        )

        agreement, education_info = self.create_agreement_and_education_info(kw, student, customer)

        return student, agreement, education_info

    def create_agreement_and_education_info(self, kw, student, customer):
        if kw.get('initial_plan_id'):
            initialPlan = model.Plan.get(int(kw.initial_plan_id))
        else:
            initialPlan = None

        if kw.get('initial_plan_student_wish_id'):
            initialPlanStudentWish = model.Plan.get(int(kw.initial_plan_student_wish_id))
        else:
            initialPlanStudentWish = initialPlan

        if kw.get('information_source_id'):
            informationSource = model.InformationSource.get(int(kw.information_source_id))
        else:
            informationSource = None

        if kw.get('event_id'):
            event = model.Event.get(int(kw.event_id))
        else:
            event = None

        agreement = model.StudentAgreement(
            student=student,
            customer=customer,
            organization=model.Organization.get(int(kw.organization_id)),
            trend=model.Trend.get(int(kw.trend_id)),
            informationSource=informationSource,
            event=event,
            customerTariff=model.CustomerTariff.get(int(kw.customer_tariff_id)),
            initialPlan=initialPlan,
            initialPlanStudentWish=initialPlanStudentWish,
            dateEnterAgreement=kw.date_enter_agreement,
        )

        if not kw.get('testResultBasic'):
            kw.testResultBasic = None

        if not kw.get('testResultProf'):
            kw.testResultProf = ''

        education_info = model.EducationInfo(
            testResultBasic=kw.testResultBasic,
            testResultProf=kw.testResultProf,
            studentAgreement=agreement
        )

        return agreement, education_info

exposed = AgreementController()
